#!/bin/bash -e

usage() {
  echo "usage: $0"
  echo
  echo "Required Variables:"
  echo
  echo "  DOMAIN"
  echo "  ROOT_CA    Path to root CA certificate"
  echo "  ROOT_CRT   Path to root/wildcard certificate"
  echo "  ROOT_KEY   Path to root/wildcard private key"
  echo "  JWT_CRT    Path to Token Auth certificate"
  echo "  JWT_KEY    Path to Token Auth private key"
  echo "  JWT_KID    Path to KeyID for the Token Auth certificate"
  echo "  VPN_CA     Path to the VPN CA certificate"
  echo "  VPN_CRT    Path to the VPN server certificate"
  echo "  VPN_KEY    Path to the VPN server private key"
  echo "  VPN_DH     Path to the VPN server Diffie Hellman parameters"
  echo "  SUPERUSER_EMAIL     Email address of the superuser"
  echo "  SUPERUSER_PASSWORD  Password of the superuser"
  echo
}

for var in DOMAIN ROOT_CA ROOT_CRT ROOT_KEY JWT_CRT JWT_KEY JWT_KID VPN_CA VPN_CRT VPN_KEY VPN_DH SUPERUSER_EMAIL SUPERUSER_PASSWORD; do
  if [ -z "${!var-}" ]; then
    usage
    exit 1
  fi
done

randstr() {
  LC_CTYPE=C tr -dc A-Za-z0-9 < /dev/urandom | fold -w "${1:-32}" | head -n 1
}

b64encode() {
    echo "$@" | base64 --wrap=0 2>/dev/null || echo "$@" | base64 --break=0 2>/dev/null
}

b64file() {
  b64encode "$(cat "$@")"
}

# buckets to create in the S3 service...
REGISTRY2_S3_BUCKET="registry-data"

cat <<STR
export OPENBALENA_PRODUCTION_MODE=false
export OPENBALENA_COOKIE_SESSION_SECRET=$(randstr 32)
export OPENBALENA_HOST_NAME=$DOMAIN
export OPENBALENA_JWT_SECRET=$(randstr 32)
export OPENBALENA_REGISTRY2_S3_BUCKET=${REGISTRY2_S3_BUCKET}
export OPENBALENA_RESINOS_REGISTRY_CODE=$(randstr 32)
export OPENBALENA_ROOT_CA=$(b64file "${ROOT_CA}")
export OPENBALENA_ROOT_CRT=$(b64file "${ROOT_CRT}")
export OPENBALENA_ROOT_KEY=$(b64file "${ROOT_KEY}")
export OPENBALENA_TOKEN_AUTH_BUILDER_TOKEN=$(randstr 64)
export OPENBALENA_TOKEN_AUTH_PUB=$(b64file "$JWT_CRT")
export OPENBALENA_TOKEN_AUTH_KEY=$(b64file "$JWT_KEY")
export OPENBALENA_TOKEN_AUTH_KID=$(b64file "$JWT_KID")
export OPENBALENA_VPN_CA=$(b64file "$VPN_CA")
export OPENBALENA_VPN_CA_CHAIN=$(b64file "$VPN_CA")
export OPENBALENA_VPN_SERVER_CRT=$(b64file "$VPN_CRT")
export OPENBALENA_VPN_SERVER_KEY=$(b64file "$VPN_KEY")
export OPENBALENA_VPN_SERVER_DH=$(b64file "$VPN_DH")
export OPENBALENA_VPN_SERVICE_API_KEY=$(randstr 32)
export OPENBALENA_API_VPN_SERVICE_API_KEY=$(randstr 32)
export OPENBALENA_REGISTRY_SECRET_KEY=$(randstr 32)
export OPENBALENA_S3_ACCESS_KEY=$(randstr 32)
export OPENBALENA_S3_BUCKETS="${REGISTRY2_S3_BUCKET}"
export OPENBALENA_S3_ENDPOINT="https://s3.${DOMAIN}"
export OPENBALENA_S3_REGION=us-east-1
export OPENBALENA_S3_SECRET_KEY=$(randstr 32)
export OPENBALENA_SSH_AUTHORIZED_KEYS=
export OPENBALENA_SUPERUSER_EMAIL=$SUPERUSER_EMAIL
export OPENBALENA_SUPERUSER_PASSWORD=$(printf "%q" "${SUPERUSER_PASSWORD}")
export OPENBALENA_ACME_CERT_ENABLED=${ACME_CERT_ENABLED:-false}
STR
